// Mesh Loader
// (c) jimon game studio

#include "CMeshLoader.h"
#include "ILogManager.h"
#include "CMeshFormatLoader_JED.h"
#include "CMeshFormatLoader_SBS.h"
#include "CMeshFormatLoader_B3D.h"

namespace je
{
	namespace scene
	{
		IMPLEMENT_SINGLETON(MeshLoader,JE_ENGINE_FUNCTION_CALL)

		#define ADD_MESH_LOADER(__format)\
			CMeshFormatLoader_##__format * Loader__##__format;\
			JENEW(Loader__##__format,CMeshFormatLoader_##__format);\
			Loaders->push_back(Loader__##__format);

		//! Constructor
		CMeshLoader::CMeshLoader()
		{
			JENEW(Loaders,MeshLoadersList)

			#ifdef JE_SUPPORT_FILEFORMAT_JED
			ADD_MESH_LOADER(JED)
			#endif

			#ifdef JE_SUPPORT_FILEFORMAT_SBS
			ADD_MESH_LOADER(SBS)
			#endif

			#ifdef JE_SUPPORT_FILEFORMAT_B3D
			ADD_MESH_LOADER(B3D)
			#endif

			SetMeshLoader(this);
		}

		//! Destructor
		CMeshLoader::~CMeshLoader()
		{
			for(MeshLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				JEDELETE(*Iter)

			Loaders->clear();

			JEDELETE(Loaders)

			SetMeshLoader(NULL);
		}

		//! Load Mesh
		jeMesh * CMeshLoader::LoadMesh(core::IBuffer * DataBuffer,video::IRender * Render)
		{
			for(MeshLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter)->CanWorkWithThis(DataBuffer))
					return (*Iter)->LoadMesh(DataBuffer,Render);

			JELOG_W("Mesh file format not supported")

			return NULL;
		}

		//! Save Mesh
		void CMeshLoader::SaveMesh(core::IBuffer * Buffer,jeMesh * Mesh,MeshFormat Format)
		{
			for(MeshLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter)->GetMeshFormat() == Format)
				{
					(*Iter)->SaveMesh(Buffer,Mesh);
					return;
				}
		}

		//! Register Format Loader
		void CMeshLoader::RegisterFormatLoader(IMeshFormatLoader * FormatLoader)
		{
			Loaders->push_back(FormatLoader);
			FormatLoader->Grab();
		}

		//! UnRegister Format Loader
		void CMeshLoader::UnRegisterFormatLoader(IMeshFormatLoader * FormatLoader)
		{
			for(MeshLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter) == FormatLoader)
				{
					FormatLoader->Drop();
					Loaders->erase(Iter);
				}
		}

		//! Get Format Loader
		IMeshFormatLoader * CMeshLoader::GetFormatLoader(MeshFormat Format)
		{
			for(MeshLoadersList::Iterator Iter = Loaders->begin();Iter != Loaders->end();Iter++)
				if((*Iter)->GetMeshFormat() == Format)
					return *Iter;
			return NULL;
		}

	}
}
